package com.ruoyi.web.controller.system;

import cn.hutool.core.date.DateTime;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.Server.BT.TorrentService;
import com.ruoyi.web.Server.sys.ResPassKeyService;
import com.ruoyi.web.controller.common.base.Result;
import com.ruoyi.web.dao.sys.ResPassKeyMapper;
import com.ruoyi.web.domain.sys.UserPassKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;

import java.time.LocalDateTime;

/**
 * 注册验证
 * 
 * @author ruoyi
 */
@RestController
public class SysRegisterController
{
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TorrentService torrentService;

    @Autowired
    private ResPassKeyService passKeyService;

    @Autowired
    private ResPassKeyMapper passkeyManager;

    @Autowired
    private ISysUserService userService;
//    private UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody RegisterBody user)
    {
        try {
            Integer user_id = registerUser(user);
            // 创建用户凭证实体
            torrentService.createCredential(user_id);
            return Result.ok();
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    /**
     * 注册
     */
    public Integer registerUser(RegisterBody registerBody) {
        String passkey = registerBody.getPassKey();
        String username = registerBody.getUserName();

        // 1. 校验邀请码
        if (!passKeyService.isValidPassKey(passkey)) {
            throw new RuntimeException("邀请码无效或已过期");
        }
        // 3. 创建用户
        SysUser user = new SysUser();
        user.setUserName(username);
        user.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
        user.setUserName(registerBody.getUserName());
        user.setNickName(registerBody.getUserName());
        user.setCreateTime(DateTime.now());
        user.setDelFlag("0");
        // 2. 校验用户名是否重复
        if (!userService.checkUserNameUnique(user)) {
            throw new RuntimeException("用户名已存在");
        }

        boolean success = userService.registerUser(user);

        if (!success) {
            throw new RuntimeException("用户注册失败");
        }

        // 4. 获取创建的用户ID
        SysUser createdUser = userService.selectUserByUserName(username);
        if (createdUser == null) {
            throw new RuntimeException("用户创建失败");
        }

        // 5. 标记邀请码为已使用（可选）
        UserPassKey passKey = passkeyManager.getByPasskey(passkey);
        if (passKey != null) {
            passKey.setStatus(0); // 设置为已使用
            passkeyManager.updateById(passKey);
            redisCache.deleteObject("passkey:" + passkey);
        }

        return createdUser.getUserId().intValue();
    }

}
